/*
 * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */

#include <stdint.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "tinyusb.h"
#include "tusb_cdc_acm.h"
#include "sdkconfig.h"

static const char *TAG = "example";

void send_task(void *pvParameters)
{
    uint8_t keycode[6] = {0};
    keycode[0] = HID_KEY_A;
    while (1)
    {
        if (!tud_hid_ready())
            continue;
        tud_hid_keyboard_report(1, 0, keycode);
        vTaskDelay(pdMS_TO_TICKS(100));
        tud_hid_keyboard_report(1, 0, NULL);
        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}

// Invoked when received GET_REPORT control request
// Application must fill buffer report's content and return its length.
// Return zero will cause the stack to STALL request
uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t *buffer, uint16_t reqlen)
{
    // TODO not Implemented
    (void)instance;
    (void)report_id;
    (void)report_type;
    (void)buffer;
    (void)reqlen;

    return 0;
}

// Invoked when received SET_REPORT control request or
// received data on OUT endpoint ( Report ID = 0, Type = 0 )
void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const *buffer, uint16_t bufsize)
{
    (void)instance;

    // if (report_type == HID_REPORT_TYPE_OUTPUT)
    // {
    //     // Set keyboard LED e.g Capslock, Numlock etc...
    //     if (report_id == REPORT_ID_KEYBOARD)
    //     {
    //         // bufsize should be (at least) 1
    //         if (bufsize < 1)
    //             return;

    //         uint8_t const kbd_leds = buffer[0];

    //         if (kbd_leds & KEYBOARD_LED_CAPSLOCK)
    //         {
    //             // Capslock On: disable blink, turn led on
    //             xTimerStop(blinky_tm, portMAX_DELAY);
    //             board_led_write(true);
    //         }
    //         else
    //         {
    //             // Caplocks Off: back to normal blink
    //             board_led_write(false);
    //             xTimerStart(blinky_tm, portMAX_DELAY);
    //         }
    //     }
    // }
}

void app_main(void)
{
    ESP_LOGI(TAG, "USB initialization");

    tinyusb_config_t tusb_cfg = {}; // the configuration using default values
    ESP_ERROR_CHECK(tinyusb_driver_install(&tusb_cfg));

    ESP_LOGI(TAG, "USB initialization DONE");
    // xTaskCreate(send_task, "send_task", 1024 * 8, NULL, 5, NULL);
}
